<!DOCTYPE html>
<html>
<head>
    <title>支付页面</title>
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <!-- 引入字体图标增强视觉表现 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" th:href="@{/jquery-weui/lib/weui.css}">
    <link rel="stylesheet" th:href="@{/jquery-weui/css/jquery-weui.css}">
    <link rel="stylesheet" th:href="@{/jquery-weui/css/demos.css}">
    <style>
        /* 基础样式重置与全局设置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
        }

        html {
            height: 100%;
            touch-action: manipulation;
            background-color: #f5f7fa;
        }

        body {
            width: 100%;
            height: 100%;
            -webkit-text-size-adjust: none;
            color: #333;
            line-height: 1.5;
        }

        .no-select {
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
        }

        /* 顶部导航栏 */
        .top-nav {
            height: 55px;
            background-color: #fff;
            display: flex;
            align-items: center;
            padding: 0 15px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            position: relative;
            z-index: 10;
        }

        .nav-btn {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: background-color 0.2s;
        }

        .nav-btn:hover {
            background-color: #f0f0f0;
        }

        .nav-btn img {
            width: 25px;
            height: 25px;
        }

        .nav-title {
            flex: 1;
            text-align: center;
            font-size: 18px;
            font-weight: 600;
            color: #1a1a1a;
        }

        /* 主体内容区域 */
        .bd {
            width: 100%;
            height: calc(100% - 55px);
            overflow-y: auto;
            padding-bottom: 30px;
        }

        .page__bd {
            padding: 15px;
        }

        /* 付款信息卡片 */
        .payment-card {
            background-color: #fff;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .payment-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
        }

        .payment-card__title {
            font-size: 16px;
            color: #666;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
        }

        .payment-card__title i {
            margin-right: 8px;
            color: #4285f4;
        }

        .payment-info {
            font-size: 18px;
            line-height: 1.6;
            color: #1a1a1a;
            padding-left: 24px;
            position: relative;
        }

        .payment-info::before {
            content: "";
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            width: 4px;
            background: linear-gradient(180deg, #4285f4 0%, #34a853 100%);
            border-radius: 2px;
        }

        /* 按钮样式 */
        .btn-group {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
        }

        .main-btn {
            flex: 1;
            height: 52px;
            border-radius: 12px;
            border: none;
            font-size: 17px;
            font-weight: 600;
            color: #fff;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 14px rgba(0, 0, 0, 0.15);
        }

        .main-btn:active {
            transform: scale(0.98);
        }

        .btn-direct {
            background: linear-gradient(135deg, #34a853 0%, #2e7d32 100%);
        }

        .btn-direct:hover {
            box-shadow: 0 6px 18px rgba(52, 168, 83, 0.3);
        }

        .btn-direct.disabled {
            background: #e0e0e0;
            color: #9e9e9e;
            box-shadow: none;
            cursor: not-allowed;
        }

        .btn-code {
            background: linear-gradient(135deg, #4285f4 0%, #2861c5 100%);
        }

        .btn-code:hover {
            box-shadow: 0 6px 18px rgba(66, 133, 244, 0.3);
        }

        /* 兑换码区域 */
        .exchange-container {
            background-color: #fff;
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            overflow: hidden;
            max-height: 0;
            opacity: 0;
            transition: max-height 0.4s ease, opacity 0.4s ease, padding 0.4s ease;
        }

        .exchange-container.show {
            max-height: 300px;
            opacity: 1;
            padding: 20px;
        }

        .exchange-title {
            font-size: 16px;
            color: #666;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
        }

        .exchange-title i {
            margin-right: 8px;
            color: #4285f4;
        }

        .exchange-input {
            position: relative;
            margin-bottom: 18px;
        }

        .exchange-input .weui-input {
            height: 50px;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            padding: 0 15px;
            font-size: 16px;
            color: #1a1a1a;
            transition: all 0.3s;
        }

        .exchange-input .weui-input:focus {
            border-color: #4285f4;
            box-shadow: 0 0 0 3px rgba(66, 133, 244, 0.1);
            outline: none;
        }

        .btn-confirm {
            width: 100%;
            height: 52px;
            background: linear-gradient(135deg, #5f63f2 0%, #4245e4 100%);
            border-radius: 12px;
            border: none;
            font-size: 17px;
            font-weight: 600;
            color: #fff;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 14px rgba(95, 99, 242, 0.2);
        }

        .btn-confirm:active {
            transform: scale(0.98);
        }

        .btn-confirm:hover {
            box-shadow: 0 6px 18px rgba(95, 99, 242, 0.3);
        }

        /* 加载动画优化 */
        .weui-loading {
            width: 24px;
            height: 24px;
            border-width: 3px;
        }
    </style>
</head>

<body class="no-select">
<!-- 顶部导航栏 -->
<div class="top-nav">
    <div class="nav-btn" onclick="window.history.back();">
        <img src="/stamp/image/ht.png" alt="返回">
    </div>
    <div class="nav-btn" onclick="zy();">
        <img src="/stamp/image/zy.png" alt="主页">
    </div>
    <div class="nav-title">支付详情</div>
    <div class="nav-btn" onclick="window.location.reload()">
        <img src="/stamp/image/sx.png" alt="刷新">
    </div>
</div>

<div class="bd">
    <div class="page__bd">
        <!-- 付款信息卡片 -->
        <div class="payment-card">
            <div class="payment-card__title">
                <i class="fas fa-info-circle"></i>付款信息
            </div>
            <div class="payment-info" id="msg"></div>
        </div>

        <!-- 主按钮组 -->
        <div class="btn-group">
            <button class="main-btn btn-direct" onclick="createPay();">
                <i class="fas fa-credit-card"></i>直接付款
            </button>
            <button class="main-btn btn-code" onclick="toggleExchangeArea();">
                <i class="fas fa-ticket-alt"></i>使用兑换码
            </button>
        </div>

        <!-- 兑换码区域 -->
        <div class="exchange-container" id="exchangeArea">
            <div class="exchange-title">
                <i class="fas fa-gift"></i>兑换码兑换
            </div>
            <div class="exchange-input">
                <input class="weui-input" type="text" id="exchangeCode" style="text-transform: uppercase" placeholder="请输入兑换码">
            </div>
            <button class="btn-confirm" onclick="dh();">
                <i class="fas fa-exchange-alt"></i>确认兑换
            </button>
        </div>
    </div>
</div>

<!-- 地址弹窗（保留原有功能） -->
<input id="xm" name="xm" type="hidden" value="">
<div id="addrPopup" class="weui-popup__container">
    <div class="weui-popup__overlay"></div>
    <div class="weui-popup__modal" style="background-color:#F0F0F0;">
        <iframe width="100%;" id="addr_iframe" height="100%;" style="border:none;" src=""></iframe>
    </div>
</div>

</body>
<script type="text/javascript" th:src="@{/jquery-weui/lib/jquery-2.1.4.js}" charset="utf-8"></script>
<script type="text/javascript" th:src="@{/jquery-weui/js/jquery-weui.js}" charset="utf-8"></script>
<script type="text/javascript" th:src="@{/jsfiles/crypto-js.min.js?t=1}" charset="utf-8"></script>
<script type="text/javascript" th:src="@{/jsfiles/com.js?t=12}" charset="utf-8"></script>
<script type="text/javascript" th:src="@{/layer/mobile/layer.js}" charset="utf-8"></script>
<script type="text/javascript" th:src="@{/jsfiles/jweixin-1.6.0.js}" charset="utf-8"></script>
<script type="text/javascript">
    // 禁止双击放大
    document.addEventListener('dblclick', function(e) {
        e.preventDefault();
    }, { passive: false });

    var id = "[[${id}]]";
    var yw = "[[${yw}]]";
    var ywcs = "[[${ywcs}]]";
    var adminUrl = "[[${adminUrl}]]";
    var url = "[[${serverUrl}]]/stamp/h5/api/";
    var dz = window.location.href;
    dz = dz.replace(/&/g, "$");

    // 初始化数据
    function init_data(){
        $.showLoading("数据加载中...");
        var jsonData = {
            id: id,
            yw: yw,
            ywcs: ywcs,
            timestamp:new Date().getTime()
        };
        var sendStr = {
            data:encrypt_str(JSON.stringify(jsonData),localStorage.getItem("a_h5"),localStorage.getItem("b_h5"))
        };
        $.ajax({
            type:"post",
            url:url+"pay_info",
            data:JSON.stringify(sendStr),
            dataType:"json",
            timeout : 10*1000,
            crossDomain: true,
            contentType: 'application/json;charset=UTF-8',
            headers: {
                "token": localStorage.getItem("token_h5")
            },
            beforeSend: function(request) {
                request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            },
            success:function(result){
                if (result.code==0) {
                    let rtn = decrypt_str(result.data, localStorage.getItem("a_h5"), localStorage.getItem("b_h5"));
                    console.info("rtn:"+rtn);
                    let d = JSON.parse(rtn);
                    $("#msg").html(d.msg);
                    $("#xm").val(d.xm);
                    if (d.sffk=="1"){
                        // 已付款状态处理
                        const directBtn = document.querySelector('.btn-direct');
                        directBtn.classList.add('disabled');
                        directBtn.innerHTML = '<i class="fas fa-check"></i>已付款';
                        directBtn.onclick = null;
                    }
                }
            },
            error:function(result){},
            complete:function(){
                $.hideLoading();
            }
        });
    }

    init_data();

    // 切换兑换码区域显示/隐藏（带动画）
    function toggleExchangeArea() {
        const exchangeArea = document.getElementById("exchangeArea");
        exchangeArea.classList.toggle('show');
        // 显示时自动聚焦输入框
        if (exchangeArea.classList.contains('show')) {
            setTimeout(() => {
                document.getElementById("exchangeCode").focus();
            }, 300);
        } else {
            document.getElementById("exchangeCode").blur();
        }
    }

    var loadinglayer;
    // 支付发起
    function createPay() {
        try{
            loadinglayer = layer.open({type: 2});
            var jsonData = {
                id: id,
                yw: yw,
                timestamp:new Date().getTime()
            };
            var sendStr = {
                data:encrypt_str(JSON.stringify(jsonData),localStorage.getItem("a_h5"),localStorage.getItem("b_h5"))
            };
            $.ajax({
                type:"post",
                url: url+"getpayid",
                data:JSON.stringify(sendStr),
                dataType:"json",
                timeout : 10*1000,
                crossDomain: true,
                contentType: 'application/json;charset=UTF-8',
                headers: {
                    "token": localStorage.getItem("token_h5")
                },
                beforeSend: function(request) {
                    request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
                },
                success:function(result){
                    layer.close(loadinglayer);
                    if (result.code==0) {
                        let rtn = decrypt_str(result.data, localStorage.getItem("a_h5"), localStorage.getItem("b_h5"));
                        let d = JSON.parse(rtn);
                        if (is_null(d.prepay_id)){
                            layer.open({
                                content: '支付失败，没有获取到支付凭证，是否重新发起？',
                                shadeClose: false,
                                btn: ['确认', '取消'],
                                yes: function() {
                                    loadinglayer = layer.open({type: 2});
                                    createPay();
                                }
                            });
                            return;
                        }else{
                            callPay(d.appid,d.prepay_id,d.nonce_str,d.paySign,d.timestamp);
                        }
                    }
                },
                error:function(result){
                    layer.close(loadinglayer);
                    layer.open({
                        content: '申请付款失败，是否重新发起？',
                        shadeClose: false,
                        btn: ['确认', '取消'],
                        yes: function() {
                            loadinglayer = layer.open({type: 2});
                            createPay(id,yw)
                        }
                    });
                },
                complete:function(){
                    layer.close(loadinglayer);
                }
            });
        }catch (e) {
            alert(e);
        }
    }

    // 调用支付
    function callPay(appid,prepayId,nonceStr,paySign,timeStamp) {
        try{
            if (typeof window.top.WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                }
            } else {
                onBridgeReady(appid,prepayId,nonceStr,paySign,timeStamp);
            }
        }catch (e) {
            alert("callPay发生错误："+e);
        }
    }

    function onBridgeReady(appid,prepayId,nonceStr,paySign,timeStamp) {
        try {
            layer.closeAll();
            var timestamp=new Date().getTime();
            window.top.WeixinJSBridge.invoke("getBrandWCPayRequest", {
                    "appId" : ""+appid+"",
                    "timeStamp" : ""+timeStamp+"",
                    "nonceStr" : ""+nonceStr+"",
                    "package" : "prepay_id="+prepayId+"",
                    "signType" : "MD5",
                    "paySign" : ""+paySign+""
                },
                function(res) {
                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                        alert("支付成功！");
                        window.location.href=adminUrl+"/h5/myhome/index?id="+$("#xm").val();
                    }
                    if (res.err_msg == "get_brand_wcpay_request:cancel") {
                        alert("支付取消！");
                    }
                    if (res.err_msg == "get_brand_wcpay_request:fail") {
                        alert(res.err_desc);
                        alert("支付失败！");
                    }
                });
        }catch (e) {
            alert(e);
            layer.open({type: 2});
        }
    }

    // 兑换函数
    function dh() {
        const code = document.getElementById("exchangeCode").value.trim();
        if (!code) {
            layer.open({
                content: '请输入兑换码',
                skin: 'msg',
                time: 2
            });
            return;
        }
        try{
            loadinglayer = layer.open({type: 2});
            var jsonData = {
                id: id,
                dhm:code,
                yw: yw,
                timestamp:new Date().getTime()
            };
            var sendStr = {
                data:encrypt_str(JSON.stringify(jsonData),localStorage.getItem("a_h5"),localStorage.getItem("b_h5"))
            };
            $.ajax({
                type:"post",
                url: url+"getpayid_dhm",
                data:JSON.stringify(sendStr),
                dataType:"json",
                timeout : 10*1000,
                crossDomain: true,
                contentType: 'application/json;charset=UTF-8',
                headers: {
                    "token": localStorage.getItem("token_h5")
                },
                beforeSend: function(request) {
                    request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
                },
                success:function(result){
                    layer.close(loadinglayer);
                    if (result.code==0){
                        alert("兑换成功！");
                        // 兑换成功后隐藏兑换区域并清空输入
                        window.location.href=adminUrl+"/h5/myhome/index?id="+$("#xm").val();
                    }else if(result.code==6){
                        alert("用户信息丢失，请重新进入活动，我的订单然后去付款！");
                    }else{
                        alert("兑换发生错误！"+result.msg);
                    }
                },
                error:function(result){
                    layer.close(loadinglayer);
                    layer.open({
                        content: '兑换失败，是否重新发起？',
                        shadeClose: false,
                        btn: ['确认', '取消'],
                        yes: function() {
                            loadinglayer = layer.open({type: 2});
                            dh();
                        }
                    });
                },
                complete:function(){
                    layer.close(loadinglayer);
                }
            });
        }catch (e) {
            alert(e);
        }
    }

    function zy(){
        window.location.href=adminUrl+"/h5/myhome/index?id="+$("#xm").val();
    }
</script>
</body>
</html>